var express = require('express');
var router = express.Router();
var path = require('path');
var os = require('os');
var fs = require("fs");
var machine = os.type();
const log4js = require('../log_utils.js'); // 引入库
const logger = log4js.getLogger('datelog'); // 获取指定的输出源



/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('led', {title: 'Express'});
});

function readDirSync(path){
    var pa = fs.readdirSync(path);
    pa.forEach(function(ele,index){
        var info = fs.statSync(path+"/"+ele)
        if(info.isDirectory()){
            console.log("dir: "+ele)
            readDirSync(path+"/"+ele);
        }else{
            console.log("file: "+ele)
        }
    })
}

function getFiles(folder,dir){
    var files=[];
    var flag=fs.existsSync(dir);
    if(flag){
        var pa = fs.readdirSync(dir);
        pa.forEach(function(ele){
            files[files.length]='/'+folder+'/'+ele;
        });
    }
    logger.info('files:'+files);
    return files;
}

router.get('/on', function (req, res, next) {

    if (!checkPlatform()) {
        res.json({'success': false,'msg':''});
        return;
    }
    var Gpio = require('rpio2/lib').Gpio;
    var led = new Gpio(36);
    led.open(Gpio.OUTPUT, Gpio.LOW);
    led.toggle();
    res.json({'success': true});
});
router.get('/off', function (req, res, next) {
    if (!checkPlatform()) {
        res.json({'success': false,'msg':''});
        return;
    }
    var Gpio = require('rpio2/lib').Gpio;
    var led = new Gpio(36);
    led.close();
    res.json({'success': true});
});

function checkPlatform(){
    if (machine.indexOf('windows')>-1) {
        return false;
    }
    return true;
}

router.get('/os', function (req, res, next){
    var upTime = os.uptime();
    upTime = upTime/3600;
    upTime = upTime.toFixed(2)+'小时';
    var mem = os.totalmem();
    mem = mem/1024/1024/1024;
    mem = mem.toFixed(2)+'GB';
    var freeMem=os.freemem();
    freeMem = freeMem/1024/1024/1024;
    freeMem = freeMem.toFixed(2)+'GB';
    var info=[
        {name:"系统类型",value:os.type()},
        {name:"平台",value:	os.platform()},
        {name:"位数",value:os.arch()},
        {name:"发行版",value:os.release()},
        {name:"运行时间",value:upTime},
        {name:"内存",value:mem},
        {name:"空闲内存",value:freeMem},
        // {name:"网口",value:os.networkInterfaces()}
    ];
    res.json({success:true,data:info});
});

router.get('/reboot', async (req, res, next) => {
    if (!checkPlatform()) {
        res.json({'success': false,'msg':''});
        return;
    }
    var cmdStr = 'sudo reboot';
    var exec = require('child_process').exec;
    exec(cmdStr, function (err, stdout, srderr) {
        if (err) {
            console.error(srderr);
            logger.error(srderr);
            res.json({success:false,msg:''});
        } else {
            console.log(stdout);
            logger.info(stdout);
            res.json({success:true,msg:''});
        }
    });

});

router.get('/shutdown', async (req, res, next) => {
    if (!checkPlatform()) {
        res.json({'success': false,'msg':''});
        return;
    }
    var cmdStr = 'sudo shutdown now';
    var exec = require('child_process').exec;
    exec(cmdStr, function (err, stdout, srderr) {
        if (err) {
            console.error(srderr);
            logger.error(srderr);
            res.json({success:false,msg:''});
        } else {
            console.log(stdout);
            logger.info(stdout);
            res.json({success:true,msg:''});
        }
    });

});

router.get('/images', async (req, res, next) => {
    var p = path.resolve('./');
    var files = getFiles('image',p + '/public/image/');
    res.json({success:true,data:files});
});

router.get('/videos', async (req, res, next) => {
    var p = path.resolve('./');
    var files = getFiles('video',p + '/public/video/');
    res.json({success:true,data:files});
});


router.get('/image', async (req, res, next) => {
    if (!checkPlatform()) {
        res.json({'success': false,'msg':''});
        return;
    }


    var exec = require('child_process').exec;
    var cmdStr = '';
    var d = new Date();
    var f = d.getTime();
    var time = req.query.time;
    time = time * 1000;
    var p = path.resolve('./');
    console.log('path', p);
    var video_path = '/image/'+f;
    f = p + '/public/image/' + f;
    fs.mkdir(p + '/public/image/',function(err){
        if (err) {
            return console.error(err);
        }
    });
    cmdStr = 'raspistill -v -o  ' + f + '.jpg';
    exec(cmdStr, function (err, stdout, srderr) {
        if (err) {
            console.error(srderr);
        } else {
            console.log(stdout);
        }
        console.log('====================================');
        console.log(cmdStr);
        logger.info(cmdStr);
        console.log('====================================');
        res.json({success: true, filename: video_path + '.jpg'});

    });

});


router.get('/camera', async (req, res, next) => {

    var fs = require("fs");
    var exec = require('child_process').exec;
    var cmdStr = '';
    var d = new Date();
    var f = d.getTime();
    var time = req.query.time;
    time = time * 1000;
    var p = path.resolve('./');
    console.log('path', p);
    logger.info('path', p);
    var video_path = '/video/'+f;
    f = p + '/public/video/' + f;
    fs.mkdir(p + '/public/video/',function(err){
        if (err) {
            return console.error(err);
        }
    });
    cmdStr = 'raspivid -t ' + time + ' -o ' + f + '.h264';

    exec(cmdStr, function (err, stdout, srderr) {
        if (err) {
            console.error(srderr);
        } else {
            console.log(stdout);
        }
        console.log('====================================');
        console.log(cmdStr);
        logger.info(cmdStr);
        console.log('====================================');
        cmdStr = 'sudo MP4Box -add ' + f + '.h264 ' + f + '.mp4';
        exec(cmdStr, function (err, stdout, srderr) {
            if (err) {
                console.error(srderr);
            } else {
                console.log(stdout);
            }
            console.log('====================================');
            console.log(cmdStr);
            logger.info(cmdStr);
            console.log('====================================');

            fs.unlink(f + '.h264', function (err) {
                if (err) {
                    return console.error(err);
                }
                console.log("文件删除成功！");
                res.json({success: true, filename: video_path + '.mp4'});
            });
        });
    });

});


router.get('/cmd', function (req, res, next) {

    var exec = require('child_process').exec;
    var cmdStr = 'ifconfig | grep 172';
    cmdStr = req.query.cmd;
    exec(cmdStr, function (err, stdout, srderr) {
        if (err) {
            console.error(srderr);
            logger.warn(srderr);
            res.send(srderr)
        } else {
            console.log(stdout);
            logger.info(stdout);
            res.send(stdout)
        }
    });


});


module.exports = router;
